package com.luck.picture.lib;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;

import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.DoubleUtils;

import java.io.Serializable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * author：luck
 * project：PictureSelector
 * package：com.luck.picture.lib
 * describe：for PictureSelector's media selection.
 * email：893855882@qq.com
 * data：2017/5/24
 */

public final class PictureSelector {

    /**
     PictureSelector.create(getActivity())
     .openGallery(chooseMode)// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
     .theme(themeId)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
     .maxSelectNum(9)// 最大图片选择数量
     .minSelectNum(1)// 最小选择数量
     .imageSpanCount(4)// 每行显示个数
     .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选, PictureConfig.SINGLE
     .previewImage(true)// 是否可预览图片
     .previewVideo(true)// 是否可预览视频
     .enablePreviewAudio(true) // 是否可播放音频
     .isCamera(false)// 是否显示拍照按钮
     .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
     //.imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
     .setOutputCameraPath("/CustomPath")// 自定义拍照保存路径
     .enableCrop(false)// 是否裁剪
     .compress(false)// 是否压缩
     .synOrAsy(true)//同步true或异步false 压缩 默认同步
     //.compressSavePath(getPath())//压缩图片保存地址
     //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
     .glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
     .isGif(true)// 是否显示gif图片
     //                .freeStyleCropEnabled(true)// 裁剪框是否可拖拽
     //                .circleDimmedLayer(false)// 是否圆形裁剪
     //                .showCropFrame(true)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false
     //                .showCropGrid(true)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false
     .openClickSound(true)// 是否开启点击声音
     .selectionMedia(selectList)// 是否传入已选图片
     .withAspectRatio(3, 2)// 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
     //                    .isDragFrame(false)// 是否可拖动裁剪框(固定)
     //                    .videoMaxSecond(15)
     //                    .videoMinSecond(10)
     //.previewEggs(false)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中)
     //.cropCompressQuality(90)// 裁剪压缩质量 默认100
     .minimumCompressSize(100)// 小于100kb的图片不压缩
     //.cropWH()// 裁剪宽高比，设置如果大于图片本身宽高则无效
     //.rotateEnabled(true) // 裁剪是否可旋转图片
     //.scaleEnabled(true)// 裁剪是否可放大缩小图片
     //.videoQuality()// 视频录制质量 0 or 1
     //.videoSecond()//显示多少秒以内的视频or音频也可适用
     //.recordVideoSecond()//录制视频秒数 默认60s
     .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
     */


    private final WeakReference<Activity> mActivity;
    private final WeakReference<Fragment> mFragment;

    private PictureSelector(Activity activity) {
        this(activity, null);
    }

    private PictureSelector(Fragment fragment) {
        this(fragment.getActivity(), fragment);
    }

    private PictureSelector(Activity activity, Fragment fragment) {
        mActivity = new WeakReference<>(activity);
        mFragment = new WeakReference<>(fragment);
    }

    /**
     * Start PictureSelector for Activity.
     *
     * @param activity
     * @return PictureSelector instance.
     */
    public static PictureSelector create(Activity activity) {
        return new PictureSelector(activity);
    }

    /**
     * Start PictureSelector for Fragment.
     *
     * @param fragment
     * @return PictureSelector instance.
     */
    public static PictureSelector create(Fragment fragment) {
        return new PictureSelector(fragment);
    }

    /**
     * @param mimeType Select the type of picture you want，all or Picture or Video .
     * @return LocalMedia PictureSelectionModel
     */
    public PictureSelectionModel openGallery(int mimeType) {
        return new PictureSelectionModel(this, mimeType);
    }

    /**
     * @param mimeType Select the type of picture you want，Picture or Video.
     * @return LocalMedia PictureSelectionModel
     */
    public PictureSelectionModel openCamera(int mimeType) {
        return new PictureSelectionModel(this, mimeType, true);
    }

    /**
     * 外部预览时设置样式
     *
     * @param themeStyle
     * @return
     */
    public PictureSelectionModel themeStyle(int themeStyle) {
        return new PictureSelectionModel(this, PictureMimeType.ofImage()).theme(themeStyle);
    }

    /**
     * @param data
     * @return Selector Multiple LocalMedia
     */
    public static List<LocalMedia> obtainMultipleResult(Intent data) {
        List<LocalMedia> result = new ArrayList<>();
        if (data != null) {
            result = (List<LocalMedia>) data.getSerializableExtra(PictureConfig.EXTRA_RESULT_SELECTION);
            if (result == null) {
                result = new ArrayList<>();
            }
            return result;
        }
        return result;
    }

    /**
     * @param data
     * @return Put image Intent Data
     */
    public static Intent putIntentResult(List<LocalMedia> data) {
        return new Intent().putExtra(PictureConfig.EXTRA_RESULT_SELECTION, (Serializable) data);
    }

    /**
     * @param bundle
     * @return get Selector  LocalMedia
     */
    public static List<LocalMedia> obtainSelectorList(Bundle bundle) {
        List<LocalMedia> selectionMedias;
        if (bundle != null) {
            selectionMedias = (List<LocalMedia>) bundle
                    .getSerializable(PictureConfig.EXTRA_SELECT_LIST);
            return selectionMedias;
        }
        selectionMedias = new ArrayList<>();
        return selectionMedias;
    }

    /**
     * @param selectedImages
     * @return put Selector  LocalMedia
     */
    public static void saveSelectorList(Bundle outState, List<LocalMedia> selectedImages) {
        outState.putSerializable(PictureConfig.EXTRA_SELECT_LIST, (Serializable) selectedImages);
    }

    /**
     * set preview image
     *
     * @param position
     * @param medias
     */
    public void externalPicturePreview(int position, List<LocalMedia> medias) {
        if (!DoubleUtils.isFastDoubleClick()) {
            Intent intent = new Intent(getActivity(), PictureExternalPreviewActivity.class);
            intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, (Serializable) medias);
            intent.putExtra(PictureConfig.EXTRA_POSITION, position);
            getActivity().startActivity(intent);
            getActivity().overridePendingTransition(R.anim.a5, 0);
        }
    }

    /**
     * set preview image
     *
     * @param position
     * @param medias
     * @param directory_path
     */
    public void externalPicturePreview(int position, String directory_path, List<LocalMedia> medias) {
        if (!DoubleUtils.isFastDoubleClick()) {
            Intent intent = new Intent(getActivity(), PictureExternalPreviewActivity.class);
            intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, (Serializable) medias);
            intent.putExtra(PictureConfig.EXTRA_POSITION, position);
            intent.putExtra(PictureConfig.DIRECTORY_PATH, directory_path);
            getActivity().startActivity(intent);
            getActivity().overridePendingTransition(R.anim.a5, 0);
        }
    }

    /**
     * set preview video
     *
     * @param path
     */
    public void externalPictureVideo(String path) {
        if (!DoubleUtils.isFastDoubleClick()) {
            Intent intent = new Intent(getActivity(), PictureVideoPlayActivity.class);
            intent.putExtra("video_path", path);
            getActivity().startActivity(intent);
        }
    }

    /**
     * set preview audio
     *
     * @param path
     */
    public void externalPictureAudio(String path) {
        if (!DoubleUtils.isFastDoubleClick()) {
            Intent intent = new Intent(getActivity(), PicturePlayAudioActivity.class);
            intent.putExtra("audio_path", path);
            getActivity().startActivity(intent);
            getActivity().overridePendingTransition(R.anim.a5, 0);
        }
    }

    /**
     * @return Activity.
     */
    @Nullable
    Activity getActivity() {
        return mActivity.get();
    }

    /**
     * @return Fragment.
     */
    @Nullable
    Fragment getFragment() {
        return mFragment != null ? mFragment.get() : null;
    }

}
